// pages/me/storeSetting/storeSetting.js
import { china } from '../../../utils/china-area'
import { baseUrl } from "../../../config";
import * as util from '../../../utils/util';
import * as API from '../../../api/store';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    form:{
      shopName:null,
      shopLogo:'',
      phone:null,
      openingTime:'08:00',
      closingTime:'20:00',
      city: "",
      area: "",
      province: "",
      merchantsPhotoDtos: [
        { img: '' },
        { img: '' },
        { img: '' },
        { img: '' }
      ],
      storeTopBackground: "",
      storeAddress: null,
      storeAnnouncement: null
    },
    isOk: false, // 是否配置门店
    id: null,
    showAddressPicker: false,
    showOpenPicker: false,
    showClosePicker: false,
    provinces: [],
    areas: [],
    cities: [],
    hours:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23],
    minus:[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59],
    showPicker: '',
    changeTrade: false,
    changePlace: false,
    changeType: false,

    
    oldProvince: 0,
    oldCity: 0,
    oldArea: 0,
    
    
  },
  uploadImg() {
    let that = this
    const token = wx.getStorageSync('token');
    wx.chooseImage({
      count: 1,
      sourceType: ['album', 'camera'],
      success(res) {
        wx.showLoading({
          title: '正在上传',
        })
        let tempFilePaths = res.tempFilePaths
        if (res.tempFiles[0].size > 4096) {
          wx.hideLoading();
          wx.showToast({
            icon: 'none',
            title: '单张张片超过4M,请重新添加'
          });
          return
        } else {
          wx.uploadFile({
            url: baseUrl + '/app/upload', //仅为示例，非真实的接口地址
            filePath: tempFilePaths[0],
            header: { 'Authorization': token},
            name: 'files',
            formData: {},
            success(res) {
              let data = JSON.parse(res.data)
              wx.hideLoading();
              if(data.code=='200'){
                let commodityImg = 'form.shopLogo'
                that.setData({
                  [commodityImg]: data.data.path||''
                })
              } else {
                wx.showToast({
                  icon: 'none',
                  title: '图片上传失败'
                });
              }
              
              
            }
          })
      }
    }
    })
  },
  uploadImgBack(){
    let that = this
    const token = wx.getStorageSync('token');
    wx.chooseImage({
      count: 1,
      sourceType: ['album', 'camera'],
      success(res) {
        wx.showLoading({
          title: '正在上传',
        })
        let tempFilePaths = res.tempFilePaths
        // if (res.tempFiles[0].size > 4096) {
        //   wx.hideLoading();
        //   wx.showToast({
        //     icon: 'none',
        //     title: '单张张片超过4M,请重新添加'
        //   });
        //   return
        // } else {
          wx.uploadFile({
            url: baseUrl + '/app/upload', //仅为示例，非真实的接口地址
            filePath: tempFilePaths[0],
            header: { 'Authorization': token},
            name: 'files',
            formData: {},
            success(res) {
              let data = JSON.parse(res.data)
              wx.hideLoading();
              if(data.code=='200'){
                let commodityImg = 'form.storeTopBackground'
                that.setData({
                  [commodityImg]: data.data.path||''
                })
              } else {
                wx.showToast({
                  icon: 'none',
                  title: '图片上传失败'
                });
              }
            }
          })
      // }
    }
    })
  },
  uploadImgs(e) {
    // debugger
    let num = e.currentTarget.dataset.i
    var that = this
    const token = wx.getStorageSync('token');
    wx.chooseImage({
      count: 1,
      sourceType: ['album', 'camera'],
      success(res) {
        wx.showLoading({
          title: '正在上传',
        })
        // if (that.data.imgNum == 0) {
        //   that.setData({
        //     'imgReduce.one':imgNum
        //       })
        // }
        var tempFilePaths = res.tempFilePaths
        if (res.tempFiles[0].size > 4096) {
          wx.hideLoading();
          wx.showToast({
            icon: 'none',
            title: '单张张片超过4M,请重新添加'
          });
          return
        } else {
        // for (var i = 0; i < tempFilePaths.length; i++) {
          // that.toSmImg(tempFilePaths[i], i)
          wx.uploadFile({
            url: baseUrl + '/app/upload', //仅为示例，非真实的接口地址
            filePath: tempFilePaths[0],
            header: { 'Authorization': token},
            name: 'files',
            formData: {},
            success(res) {
              let data = JSON.parse(res.data)
              wx.hideLoading();
              if(data.code=='200'){
                let commodityImg = 'form.merchantsPhotoDtos.['+num+'].img'
                that.setData({
                  [commodityImg]: data.data.path||''
                })
              } else {
                wx.showToast({
                  icon: 'none',
                  title: '图片上传失败'
                });
              }
            }
          })
      }
      }
    })
  },
  handleshowChooseItems(e){
    console.log(e)
    let type = e.target.dataset.type
    if(type==="openingTime"){
      this.setData({
        showOpenPicker: true,
        showPicker: "show"
      })
    }else if(type==="closingTime"){
      this.setData({
        showClosePicker: true,
        showPicker: "show"
      })
    }
  },
  formSubmit: function (e) {
    util.preventMoreClick(this, () => {
          let res = e.detail.value;
          let postbody = e.detail.value
          postbody.shopLogo = this.data.form.shopLogo
          postbody.openingTime = this.data.form.openingTime
          postbody.closingTime = this.data.form.closingTime
          postbody.province = this.data.form.province
          postbody.city = this.data.form.city
          postbody.area = this.data.form.area
          postbody.merchantsPhotoDtos = this.data.form.merchantsPhotoDtos
          postbody.storeTopBackground = this.data.form.storeTopBackground
          var valid3 = validates(e.detail.value.shopName + '', '请输入店铺名称');
          if (!valid3) return;
          var valid2 = validatePhone(e.detail.value.phone + '');
          if (!valid2) return;
          var valid4 = validates(e.detail.value.storeAddress + '', '请输入门店位置');
          if (!valid4) return;
          var valid5 = validates(this.data.form.province + '', '请选择经营地址');
          if (!valid5) return;
          var valid6 = validates(this.data.form.city + '', '请选择经营地址');
          if (!valid6) return;
          var valid7 = validates(this.data.form.area + '', '请选择经营地址');
          if (!valid7) return;
          var valid8 = validates(this.data.form.openingTime + '', '请选择营业时间');
          if (!valid8) return;
          var valid10 = validates(this.data.form.closingTime + '', '请选择营业时间');
          if (!valid10) return;
          this.data.isOk?this.editSubmit(postbody):this.addSubmit(postbody)
          
      
    })
  },
  addSubmit: function (res) {
    wx.showLoading({})
    API.addStore(res).then(arr => {
      wx.hideLoading();
      wx.showToast({
        icon: 'success',
        title: '门店配置成功',
        duration: 1500
      });
      setTimeout(()=>{
        wx.switchTab({
          url: '../me',
        })
      },1500)
      
    }, err => {
      wx.hideLoading();
    })
  },
  editSubmit: function (res) {
    wx.showLoading({})
    API.editStore(this.data.id, res).then(arr => {
      wx.hideLoading();
      wx.showToast({
        icon: 'success',
        title: '门店修改成功',
        duration: 1500
      });
      setTimeout(()=>{
        wx.switchTab({
          url: '../me',
        })
      },1500)
      
    }, err => {
      wx.hideLoading();
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var provinces = this.getProvinces();
    var cities = this.getCities("110000");
    var areas = this.getCities("110100");
    // var trades = this.getBelong();
    // var types = this.getCompanyType();
    this.setData({
      provinces: provinces,
      cities: cities,
      areas: areas
    })
    this.getList()
  },
  getList(){
    wx.showLoading({})
    API.getStore().then(res => {
      wx.hideLoading();
      this.setData({
        form: res.data,
        isOk: true,
        id:res.data.id
      })
      // wx.showToast({
      //   icon: 'success',
      //   title: '门店配置成功',
      //   duration: 1500
      // });
      
    }, err => {
      wx.hideLoading();
    })
  },
  openAddressPicker: function () {
    var cities = this.getCities("110000");
    var areas = this.getCities("110100");
    this.setData({
      showAddressPicker: true,
      showPicker: "show",
      changePlace: false,
      cities: cities,
      areas: areas
    })
  },
  // openTypePicker: function () {
  //   this.setData({
  //     showClosePicker: true,
  //     showPicker: "show",
  //     // changeType: false
  //   })
  // },
  // openTradePicker: function () {
  //   this.setData({
  //     showOpenPicker: true,
  //     showPicker: "show",
  //     // changeTrade: false
  //   })
  // },
  closePicker: function () {
    this.setData({
      showAddressPicker: false,
      showOpenPicker: false,
      showClosePicker: false,
      showPicker: ""
    })
  },
  ensurePlace: function () {
    let city = 'form.city'
    let province = 'form.province'
    let area = 'form.area'
    this.setData({
      [area]: this.data.changePlace ? ((this.data.areas[this.data.oldArea] && this.data.areas[this.data.oldArea].label) || '') : "东城区",
      [province]: this.data.changePlace ? ((this.data.provinces[this.data.oldProvince] && this.data.provinces[this.data.oldProvince].label) || '') : "北京市",
      [city]: this.data.changePlace ? ((this.data.cities[this.data.oldCity] && this.data.cities[this.data.oldCity].label) || '') : "市辖区",
      showAddressPicker: false,
      showPicker: ""
    })
  },
  cancelPlace: function () {
    this.setData({
      showAddressPicker: false,
      showPicker: ""
    })
  },
  ensureChange: function (e) {
    var name = e.currentTarget.dataset.name;
    console.log(e)
    if (name == "open") {
      this.setData({
        trade: this.data.changeTrade ? this.data.tempTrade : "机构组织",
        showOpenPicker: false,
        showPicker: ""
      })
    } else if (name == "close") {
      this.setData({
        companyType: this.data.changeType ? this.data.tempType : "国有企业",
        showClosePicker: false,
        showPicker: ""
      })
    }
  },
  cancelChange: function (e) {
    this.setData({
      showAddressPicker: false,
      showClosePicker: false,
      showOpenPicker: false,
      showPicker: ""
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  selectProvince: function (e) {
    var value = e.currentTarget.dataset.value;
    var label = e.currentTarget.dataset.label;
    var cities = this.getcities(value)
    var areas = this.getAreas(cities[0].lavel)
    this.setData({
      province: label
    })
  },

  bindChangePlace: function (e) {
    var val = e.detail.value;
    this.setData({
      changePlace: true
    })
    if (this.data.oldProvince !== val[0]) {
      // 省控件值变化
      var province = this.data.provinces[val[0]];
      var cities = this.getCities(province.value);
      var city = cities[0];
      var areas = this.getAreas(city.value);
      this.setData({
        oldProvince: val[0],
        oldCity: 0,
        oldArea: 0,
        cities: cities,
        areas: areas
      });
    } else if (this.data.oldCity !== val[1]) {
      var city = this.data.cities[val[1]];
      var areas = this.getAreas(city.value);
      this.setData({
        oldCity: val[1],
        oldArea: 0,
        areas: areas
      });
    } else {
      this.setData({
        oldArea: val[2]
      });
    }
    var provinces = []
    provinces = this.getProvinces();
    provinces[0]
  },

  bindChangeOpen: function (e) {
    let hours = e.detail.value[0]
    let minus = e.detail.value[1]
    hours=hours>10?hours:'0'+hours
    minus=minus>10?minus:'0'+minus
    let str = 'form.openingTime'
    this.setData({
      // tempType: tempType,
      // changeType: true,
      [str]: hours+':'+minus
    })
  },

  bindChangeClose: function (e) {
    // var tempType = this.data.types[e.detail.value[0]];
    // console.log(e, '===========')
    let hours = e.detail.value[0]
    let minus = e.detail.value[1]
    hours=hours>10?hours:'0'+hours
    minus=minus>10?minus:'0'+minus
    let str = 'form.closingTime'
    this.setData({
      // tempType: tempType,
      // changeType: true,
      [str]: hours+':'+minus
    })
  },

  selectCity: function (e) {
    var value = e.currentTarget.dataset.value;
    var label = e.currentTarget.dataset.label;
    var areas = this.getAreas(value);
    let city = 'form.city'
    this.setData({
      [city]: label,
      cities: cities
    })
  },

  selectArea: function (e) {
    var value = e.currentTarget.dataset.value;
    var label = e.currentTarget.dataset.label;
    var areas = this.getAreas(value);
    this.setData({
      area: label,
      areas: areas
    })
  },

  getProvinces: function () {
    const data = china['86'];
    return this.getSelectData(data);
  },

  getCities: function (provinceId) {
    const data = china[provinceId];
    return this.getSelectData(data);
  },

  getAreas: function (cityId) {
    const data = china[cityId];
    return this.getSelectData(data);
  },

  getIdByName: function (collection, name) {
    const res = collection.map(el => el.label === name)
    if (res) {
      return res.value;
    }
    return '';
  },
  getSelectData(data) {
    if (!data) return [];
    return Object.keys(data).map(key => {
      return {
        value: key,
        label: data[key]
      };
    });
  }
})

function validatePhone(value) {
  if (!value || value.length < 1) {
    wx.showToast({
      title: '请输入手机号',
      icon: 'none'
    });
    return false;
  }
  if (!(util.validators.phone.test(value))) {
    wx.showToast({
      title: '手机号格式错误',
      icon: 'none'
    });
    return false;
  }
  return true;
}

function validates(value, info) {
  if (!value || value.length < 1) {
    wx.showToast({
      title: info,
      icon: 'none'
    });
    return false;
  }
  return true;
}